import re
import sys
import os
import pandas as pd

# 正则表达式匹配格式1
pattern1 = re.compile(r'compile method:([^:]*):[^#]*#[^#]*#([^,]+), in jit thread: text size: (\d+)bytes, compile time: ([\d.]+)ms')
# 正则表达式匹配格式2(app|third_lib_js|weekly)\w+/(.*?)/

pattern2 = re.compile(r'<JSFunction ([^ ]+) \(sfi = [^>]+\)>.*filename:.*(?:app|third_lib_js|weekly)[^/]*/(.*?)(?:/|\.).*codesize: (\d+) byte,  - took ([\d., ]+) ms')
def get_filename_without_extension(filepath):
    """获取文件名（不含后缀）"""
    basename = os.path.basename(filepath)
    filename, _ = os.path.splitext(basename)
    return filename

def parse_file(file_path, pattern1, pattern2):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    data = []

    for line in lines:
        match1 = pattern1.search(line)
        match2 = pattern2.search(line)

        if match1:
            file_name, function_name, code_size, compile_time = match1.groups()
            file_name = get_filename_without_extension(file_name)
            data.append({
                'File Name': file_name,
                'Function Name': function_name,
                'Code Size (bytes)': int(code_size),
                'Compile Time (ms)': float(compile_time)
            })
        elif match2:
            function_name, file_name, code_size, compile_times = match2.groups()
            print(function_name)
            print(file_name)
            print(code_size)
            print(compile_times)
            compile_time = sum(map(float, compile_times.split(', ')))
            data.append({
                'File Name': file_name,
                'Function Name': function_name,
                'Code Size (bytes)': int(code_size),
                'Compile Time (ms)': compile_time
            })

    return data

def main(file1, file2, output_excel):
    data1 = parse_file(file1, pattern1, pattern2)
    data2 = parse_file(file2, pattern1, pattern2)

    # 创建DataFrame
    df1 = pd.DataFrame(data1)
    df2 = pd.DataFrame(data2)
    sheet_name1 = get_filename_without_extension(file1)
    sheet_name2 = get_filename_without_extension(file2)

    # 保存到Excel文件
    with pd.ExcelWriter(output_excel, engine='openpyxl') as writer:
        df1.to_excel(writer, sheet_name=sheet_name1, index=False)
        df2.to_excel(writer, sheet_name=sheet_name2, index=False)

        # 比较两个文件中函数名完全匹配的函数
        comparison_data = []

        # 获取所有唯一的文件名
        unique_file_names = set(df1['File Name']).union(set(df2['File Name']))

        for file_name in unique_file_names:
            file_data1 = df1[df1['File Name'] == file_name]
            file_data2 = df2[df2['File Name'] == file_name]

            common_functions = set(file_data1['Function Name']) & set(file_data2['Function Name'])
            common_data1 = file_data1[file_data1['Function Name'].isin(common_functions)]
            common_data2 = file_data2[file_data2['Function Name'].isin(common_functions)]

            total_compile_time1 = common_data1['Compile Time (ms)'].sum()
            total_compile_time2 = common_data2['Compile Time (ms)'].sum()
            total_code_size1 = common_data1['Code Size (bytes)'].sum()
            total_code_size2 = common_data2['Code Size (bytes)'].sum()

            total_functions1 = len(file_data1)
            total_functions2 = len(file_data2)

            compile_time_change = (total_compile_time2 - total_compile_time1) / total_compile_time1 * 100 if total_compile_time1 != 0 else float('inf')

            comparison_data.append({
                'File Name': file_name,
                f'Total Functions ({sheet_name1})': total_functions1,
                f'Total Functions ({sheet_name2})': total_functions2,
                'Total Compile Time (Sheet1)': total_compile_time1,
                'Total Compile Time (Sheet2)': total_compile_time2,
                'Total Code Size (Sheet1)': total_code_size1,
                'Total Code Size (Sheet2)': total_code_size2,
                'Compile Time Change (%)': compile_time_change
            })

        comparison_df = pd.DataFrame(comparison_data)
        comparison_df.to_excel(writer, sheet_name='Comparison', index=False)

    print(f"Results written to {output_excel}")

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Usage: python compare_compile_times.py <path_to_file1> <path_to_file2> <output_excel>")
        sys.exit(1)

    file1 = sys.argv[1]
    file2 = sys.argv[2]
    output_excel = sys.argv[3]
    main(file1, file2, output_excel)